import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 20000 // request timeout
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    if (!config.headers.Authorization && store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    // 解构后端字段
    // success: 接口是否成功
    // data: 接口数据
    // message: 接口提示文案
    const { success, data, message } = response.data
    if (success) {
      console.log(data)
      return response.data
    } else {
      // 错误提示用户
      Message.error(message)
      // 抛出错误：success 为 false 时，统一按错误处理
      return Promise.reject(message)
    }
  },
  error => {
    Message.error(error.message)
    return Promise.reject(error)
  }
)

export default request
